﻿define([
  'models/abmManagers/userManager',
  'models/abmManagers/rolManager',
  'models/abmManagers/groupManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/user/common/userEdit.html',
], function (UserModel, RolModel, GroupModel, BaseTmp, FormTmp, UniqTmp) {
    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        _user: {},
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-user']").remove();
            var userMod = new UserModel();
            var _this = this;
            this._uId = $.uuid();

            userMod.GetUser(this.options.userId, function (dataUser) {
                var baseTemplate = Handlebars.compile(BaseTmp);
                var formTemplate = Handlebars.compile(FormTmp);
                var uniqTemplate = Handlebars.compile(UniqTmp);

                var cpyId = __currentSession.companyId;
                var userCompany = {};
                for (var i = 0; i < dataUser.userCompanies.length ; i++) {
                    if (cpyId == dataUser.userCompanies[i].companyId) {
                        userCompany = dataUser.userCompanies[i];
                    }
                }
                _this._user = dataUser;

                var dataBaseTemplate = {
                    id: _this._uId,
                    dataRel: "abm-user", // cuidado, ref en js
                    tmpClass: "user-edit", // cuidado, ref en css
                    title: translate("_editUser")
                };
                var dataUniqTemplate = {
                    user: dataUser,
                    userData: userCompany,
                };

                var html = baseTemplate(dataBaseTemplate);
                var html2 = formTemplate();
                var html3 = uniqTemplate(dataUniqTemplate);
                /*
                var template = Handlebars.compile(HTMLTemplate);
                var cpyId = __currentSession.companyId;
                var userCompany = {};
                for (var i = 0; i < dataUser.userCompanies.length ; i++) {
                    if (cpyId == dataUser.userCompanies[i].companyId) {
                        userCompany = dataUser.userCompanies[i];
                    }
                }
                _this._user = dataUser;
                var data = {
                    user: dataUser,
                    userData: userCompany,
                    id: _this._uId
                }
                var html = template(data);
                */

                _this.$el.append(html);
                $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);

                _this.initialValues(userCompany);
                postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                _this.addHandlers();
                $("#mainLoading").hide();
            });
        },
        initialValues: function (userCompany) {
            var _this = this;

            var rol = new RolModel();
            rol.List(userCompany.companyId, function (dataRol) {
                if (dataRol.length > 0) { // si la company tiene roles
                    
                    var rolList = [{ value: "", text: "" }];
                    for (var ii = 0; ii < dataRol.length; ii++) {
                        rolList[ii] = {
                            value: dataRol[ii].rolId,
                            text: dataRol[ii].name
                        }
                    }
                    var _rolItem = $("div[data-id='" + _this._uId + "']").find("div.user-rol a");
                    _rolItem.editable({
                        pk: 1,
                        source: rolList,
                        success: function (response, newValue) {
                            $(this).attr("data-value", newValue);
                        }
                    });
                }
            });
            
            var groups = new GroupModel();
            groups.List(userCompany.companyId, function (dataGroup) {
                if (dataGroup.length > 0) { // si la company tiene grupos
                    var groupsList = [{ value: "", text: "" }];
                    for (var i = 0; i < dataGroup.length; i++) {
                        groupsList[i] = {
                            value: dataGroup[i].groupId,
                            text: dataGroup[i].name
                        }
                    }
                    var initGroupVal = [];
                    for (var i = 0; i < userCompany.groups.length; i++) {
                        initGroupVal[i] = userCompany.groups[i].groupId;
                    }
                    var _groupItem = $("div[data-id='" + _this._uId + "']").find("div.user-group a");
                    _groupItem.editable({
                        pk: 1,
                        value: initGroupVal,
                        source: groupsList,
                        success: function (response, newValue) {
                            $(this).attr("data-value", newValue);
                        }
                    });
                }
            });
        },
        save: function () {
            var _uId = this._uId, _this = this;
            
            var _userForm = $("div[data-id='" + _uId + "']").find("form");
            if (!$(_userForm).validate().errorList.length > 0) {
                var userCompaniesData = _this._user;
                var cpyId = __currentSession.companyId;
                var _name = $("div[data-id='" + _uId + "']").find("div.user-name input").val();
                var _userLogin = $("div[data-id='" + _uId + "']").find("div.user-login input").val();
                var _password = $("div[data-id='" + _uId + "']").find("div.user-password input").val();
                var _email = $("div[data-id='" + _uId + "']").find("div.user-email input").val();
                var _state = '0' != $("div[data-id='" + _uId + "']").find("div.user-state input").val();

                var _rolId = $("div[data-id='" + _uId + "']").find("div.user-rol a div").attr("data-value");
                if (_rolId == undefined) {
                    _rolId = $("div[data-id='" + _uId + "']").find("div.user-rol a").attr("data-value");
                }

                var _groupItem = $("div[data-id='" + _this._uId + "']").find("div.user-group a");

                var assignedGroups = [];
                var auxRowGroups = $(_groupItem).attr("data-value");
                if (auxRowGroups != undefined) {
                    var splitGroups = auxRowGroups.split(",");

                    for (var h = 0; h < splitGroups.length; h++) {
                        assignedGroups[h] = {
                            groupId: splitGroups[h]
                        };
                    }
                } else {
                    var auxRowGroup = "";
                    for (var h = 0; h < _groupItem.find("div").length; h++) {
                        assignedGroups[h] = {
                            groupId: $(_groupItem.find("div")[h]).attr("data-value")
                        };
                    }
                }

                var userCompaniesData = _this._user.userCompanies;
                for (var i = 0; i < userCompaniesData.length ; i++) {
                    if (cpyId == userCompaniesData[i].companyId) {
                        userCompaniesData[i].rolId = _rolId;
                        userCompaniesData[i].groups = assignedGroups;
                    }
                }

                var user = {
                    userId: this.options.userId, fullName: _name, userLogin: _userLogin,
                    active: _state, email: _email, password: _password,
                    userCompanies: userCompaniesData
                };

                var userMod = new UserModel();
                userMod.Update(user, function () {
                    require(['controllers/abmManagers/userManager'], function (Controller) {
                        (new Controller()).show();
                    });
                });
            }
        },
        changeState: function () {
            this.checked ? $(this).attr('value', 1) : $(this).attr('value', 0);
        },
        cancel: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("div.user-state input").on("click", this.changeState);
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});